package api

import (
	"context"
	"fmt"
	"net/http"
	"net/url"
	"time"

	"dev.ixmxm.top/rms/codes"
	"dev.ixmxm.top/rms/model"
	"dev.ixmxm.top/rms/utils/log"
	"github.com/gin-gonic/gin"
)

// @Summary 获取rms日志
// @Description
// @Accept application/json
// @Produce application/json
// @Param time_from query int64 true "开始时间戳"
// @Param time_to query int64 true "结束时间戳"
// @Param level query uint8 true "日志最小等级：0=Info、1=Warn、2=Error、3=DPanic、4=Panic、5=Fatal"
// @Param page_size query int64 true "每页记录数量"
// @Param page_index query int64 true "当前页码"
// @Success 0 {object} ResponseExampleStruct "返回数据格式"
// @Success 1 {object} page.PageResultExample "data数据：分页信息"
// @Success 2 {object} []model.RMSLog "list数据：rms日志集合"
// @Tags 日志
// @Router /log/get_rms_log [get]
func (hg *HttpGateway) GetRMSLogs(ctx context.Context, params interface{}) (interface{}, codes.Code) {
	p := params.(*getRMSLogsParams)
	var from, end time.Time
	if p.TimeFrom != 0 {
		from = time.Unix(p.TimeFrom, 0)
	}
	if p.TimeTo != 0 {
		end = time.Unix(p.TimeTo, 0)
	}
	log.Infof("get rms logs:from:%s,to:%s,level:%d", from.Local(), end.Local(), p.Level)
	logs, pageResult, err := hg.dispatcher.LM().GetRMSLogsForPageFromDB(ctx, from, end, p.Level, p.Params)
	if err != nil {
		log.ErrorWithContext(ctx, "get rms logs error:", err.UnWrapError())
		return nil, err
	}
	return pageResult.Json(logs), nil
}

// @Summary 下载指定日期内的RMS日志excel文件)
// @Description
// @Accept application/json
// @Produce application/json
// @Param time_from query int64 true "开始时间戳"
// @Param time_to query int64 true "结束时间戳"
// @Param level query uint8 true "日志最小等级：0=Info、1=Warn、2=Error、3=DPanic、4=Panic、5=Fatal"
// @Success 0 {object} ResponseExample "返回数据格式"
// @Tags 日志
// @Router /log/download_excel_rms_log [get]
func (hg *HttpGateway) DownloadExcelRmsLogs(ctx context.Context, params interface{}, c *gin.Context) (interface{}, codes.Code) {
	p := params.(*getRMSLogsParams)
	var from, end time.Time
	if p.TimeFrom != 0 {
		from = time.Unix(p.TimeFrom, 0)
	}
	if p.TimeTo != 0 {
		end = time.Unix(p.TimeTo, 0)
	}
	log.Infof("get rms logs:from:%s,to:%s,level:%d", from.Local(), end.Local(), p.Level)
	logs, err := hg.dispatcher.LM().GetExportRMSLogsFromDB(ctx, from, end, p.Level)
	if err != nil {
		log.ErrorWithContext(ctx, "get rms logs error:", err.UnWrapError())
		return nil, err
	}

	var res []interface{}
	for _, log1 := range logs {
		res = append(res, &model.ExportRMSLog{
			StartTime: log1.StartTime,
			LevelStr:  log1.LevelStr,
			Msg:       log1.Msg,
		})
	}
	fileName := fmt.Sprintf("%s%s.xlsx", "RMS日志", time.Now())
	// c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
	c.Writer.Header().Add("Content-Disposition", fmt.Sprintf("attachment; filename*=UTF-8''%s", url.QueryEscape(fileName)))
	c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
	content1 := ToExcel([]string{`时间`, `级别`, `消息`}, res)
	http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content1)
	return nil, nil
}

// @Summary 获取机器人日志
// @Description
// @Accept application/json
// @Produce application/json
// @Param time_from query int64 true "开始时间戳"
// @Param time_to query int64 true "结束时间戳"
// @Param agv_id query uint8 false "机器人ID，为空时查全部"
// @Param page_size query int64 true "每页记录数量"
// @Param page_index query int64 true "当前页码"
// @Success 0 {object} ResponseExampleStruct "返回数据格式"
// @Success 1 {object} page.PageResultExample "data数据：分页信息"
// @Success 2 {object} []model.RobotLog "list数据：机器人日志集合"
// @Tags 日志
// @Router /log/get_agv_log [get]
func (hg *HttpGateway) GetRobotsLogs(ctx context.Context, params interface{}) (interface{}, codes.Code) {
	p := params.(*getRobotsLogsParams)
	var from, end time.Time
	if p.TimeFrom != 0 {
		from = time.Unix(p.TimeFrom, 0)
	}
	if p.TimeTo != 0 {
		end = time.Unix(p.TimeTo, 0)
	}
	logs, pageResult, err := hg.dispatcher.LM().GetRobotsLogsForPageFromDB(ctx, from, end, p.AgvID, p.Params)
	if err != nil {
		log.ErrorWithContext(ctx, "get robots logs error:", err.UnWrapError())
		return nil, err
	}
	return pageResult.Json(logs), nil
}

// @Summary 下载指定日期内的机器人日志excel文件)
// @Description
// @Accept application/json
// @Produce application/json
// @Param time_from query int64 true "开始时间戳"
// @Param time_to query int64 true "结束时间戳"
// @Param agv_id query uint8 false "机器人ID，为空时查全部"
// @Success 0 {object} ResponseExample "返回数据格式"
// @Tags 日志
// @Router /log/download_excel_agv_log [get]
func (hg *HttpGateway) DownloadExcelAgvLogs(ctx context.Context, params interface{}, c *gin.Context) (interface{}, codes.Code) {
	p := params.(*getRobotsLogsParams)
	var from, end time.Time
	if p.TimeFrom != 0 {
		from = time.Unix(p.TimeFrom, 0)
	}
	if p.TimeTo != 0 {
		end = time.Unix(p.TimeTo, 0)
	}
	logs, err := hg.dispatcher.LM().GetExportRobotsLogsFromDB(ctx, from, end, p.AgvID)
	if err != nil {
		log.ErrorWithContext(ctx, "get robots logs error:", err.UnWrapError())
		return nil, err
	}
	log.Infof("", logs)
	var res []interface{}
	for _, log1 := range logs {
		res = append(res, &model.ExportRobotLog{
			StartTime: log1.StartTime,
			AgvID:     log1.AgvID,
			Code:      log1.Code,
			Msg:       log1.Msg,
		})
	}
	fileName := fmt.Sprintf("%s%s%s.xlsx", "机器人日志", time.Now())
	// c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
	c.Writer.Header().Add("Content-Disposition", fmt.Sprintf("attachment; filename*=UTF-8''%s", url.QueryEscape(fileName)))
	c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
	content1 := ToExcel([]string{`时间`, `小车编号`, `错误码`, `消息`}, res)
	http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content1)
	return nil, nil
}

// @Summary 清空所有RMS日志
// @Description
// @Accept application/json
// @Produce application/json
// @Success 0 {object} ResponseExample "返回数据格式"
// @Tags 日志
// @Router /log/delete_all_rms_log [delete]
func (hg *HttpGateway) DeleteAllRmsLog(ctx context.Context, params interface{}) (interface{}, codes.Code) {
	err := hg.dispatcher.LM().DeleteAllRMSLogsFromDB(ctx)
	if err != nil {
		log.ErrorWithContext(ctx, "delete all rms logs error:", err.UnWrapError())
		return nil, err
	}
	return nil, nil
}

// @Summary 清空所有机器人日志
// @Description
// @Accept application/json
// @Produce application/json
// @Success 0 {object} ResponseExample "返回数据格式"
// @Tags 日志
// @Router /log/delete_all_agv_log [delete]
func (hg *HttpGateway) DeleteAllAgvLog(ctx context.Context, params interface{}) (interface{}, codes.Code) {
	err := hg.dispatcher.LM().DeleteAllRobotLogsFromDB(ctx)
	if err != nil {
		log.ErrorWithContext(ctx, "delete all robot logs error:", err.UnWrapError())
		return nil, err
	}
	return nil, nil
}
